package com.leiqichao.backend.controller;

import com.leiqichao.backend.common.Result;
import com.leiqichao.backend.entity.Media;
import com.leiqichao.backend.service.MediaService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/api/media")
public class MediaController {
    private final MediaService mediaService;

    public MediaController(MediaService mediaService) {
        this.mediaService = mediaService;
    }

    @PostMapping("/upload")
    public Result<Media> uploadFile(
        @RequestParam("file") MultipartFile file,
        @RequestParam("uploader") String uploaderName
    ) {
        try {
            return Result.success(mediaService.uploadFile(file, uploaderName));
        } catch (IOException e) {
            return Result.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping
    public Result<?> listFiles() {
        return Result.success(mediaService.list());
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteFile(@PathVariable Long id) {
        return mediaService.safeDelete(id) ?
            Result.success() :
            Result.error(500, "文件删除失败");
    }
}